Skip to content

Conversation

@ravishanigarapu
Copy link
Contributor

@ravishanigarapu ravishanigarapu commented May 22, 2025

πŸ“‹ Description

JIRA ID: AMM-1456

Please provide a summary of the change and the motivation behind it. Include relevant context and details.


βœ… Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • πŸ”₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • πŸ›  Refactor (change that is neither a fix nor a new feature)
  • βš™οΈ Config change (configuration file or build script updates)
  • πŸ“š Documentation (updates to docs or readme)
  • πŸ§ͺ Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • πŸš€ Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • New Features

    • Introduced centralized utilities for creating HTTP request entities and managing user agent context, enhancing consistency across the application.
    • Added functionality to inject or override the "Authorization" header in HTTP requests.
  • Refactor

    • Streamlined HTTP request preparation in multiple services by delegating header and entity creation to a utility method, reducing manual header handling and cookie extraction.
    • Improved null safety in cookie handling.
  • Bug Fixes

    • Enhanced stability by adding null checks when retrieving cookies to prevent potential errors.
  • Style

    • Improved code organization and maintainability by centralizing repeated logic.

@coderabbitai
Copy link

coderabbitai bot commented May 22, 2025

Warning

Rate limit exceeded

@ravishanigarapu has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 53 seconds before requesting another review.

βŒ› How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 81e0a2a and e06a30a.

πŸ“’ Files selected for processing (1)
  • src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1 hunks)

Walkthrough

This update centralizes and standardizes the creation of HTTP request entities across multiple service classes by introducing a new utility, RestTemplateUtil.createRequestEntity. Manual construction of headers and cookie extraction is removed from individual methods, delegating this logic to the utility. Additional supporting utilities and wrappers are introduced for handling user agent context and HTTP request headers.

Changes

File(s) Change Summary
src/main/java/com/iemr/mmu/service/cancerScreening/CSCarestreamServiceImpl.java
src/main/java/com/iemr/mmu/service/common/master/RegistrarServiceMasterDataImpl.java
src/main/java/com/iemr/mmu/service/common/transaction/CommonDoctorServiceImpl.java
src/main/java/com/iemr/mmu/service/common/transaction/CommonServiceImpl.java
src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerImpl.java
src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerTransactionalImpl.java
src/main/java/com/iemr/mmu/service/dataSyncActivity/UploadDataToServerImpl.java
src/main/java/com/iemr/mmu/service/registrar/RegistrarServiceImpl.java
src/main/java/com/iemr/mmu/service/tele_consultation/TeleConsultationServiceImpl.java
Refactored HTTP request entity creation to use RestTemplateUtil.createRequestEntity, removing manual header and cookie extraction logic from each method.
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java Added new utility class with static method createRequestEntity for consistent HTTP entity creation, handling headers, authorization, cookies, and user agent context.
src/main/java/com/iemr/mmu/utils/CookieUtil.java Made getJwtTokenFromCookie static and added null-safety for cookies array.
src/main/java/com/iemr/mmu/utils/UserAgentContext.java Introduced new utility class to manage thread-local user agent strings.
src/main/java/com/iemr/mmu/utils/http/AuthorizationHeaderRequestWrapper.java Introduced new request wrapper class to override/inject the "Authorization" HTTP header.
src/main/java/com/iemr/mmu/utils/JwtUserIdValidationFilter.java Modified filter to wrap requests with AuthorizationHeaderRequestWrapper when JWT is present and to manage user agent context for mobile clients.
src/main/java/com/iemr/mmu/utils/http/HttpInterceptor.java Updated preHandle to bypass validation if "Authorization" header is missing or empty, logging the event and returning early.

Sequence Diagram(s)

sequenceDiagram
    participant ServiceMethod
    participant RestTemplateUtil
    participant CookieUtil
    participant UserAgentContext
    participant RestTemplate

    ServiceMethod->>RestTemplateUtil: createRequestEntity(body, authorization)
    RestTemplateUtil->>CookieUtil: getJwtTokenFromCookie(request)
    RestTemplateUtil->>UserAgentContext: getUserAgent()
    RestTemplateUtil-->>ServiceMethod: HttpEntity with headers/body
    ServiceMethod->>RestTemplate: exchange(url, HttpEntity, ...)
Loading
sequenceDiagram
    participant HttpRequest
    participant JwtUserIdValidationFilter
    participant AuthorizationHeaderRequestWrapper
    participant UserAgentContext
    participant FilterChain

    HttpRequest->>JwtUserIdValidationFilter: doFilter(request)
    alt JWT in cookie or header
        JwtUserIdValidationFilter->>AuthorizationHeaderRequestWrapper: wrap(request, "")
        AuthorizationHeaderRequestWrapper->>FilterChain: doFilter(wrappedRequest)
    else Mobile User-Agent with Authorization
        JwtUserIdValidationFilter->>UserAgentContext: setUserAgent()
        JwtUserIdValidationFilter->>FilterChain: doFilter(request)
        JwtUserIdValidationFilter->>UserAgentContext: clear()
    else
        JwtUserIdValidationFilter-->>HttpRequest: 401 Unauthorized
    end
Loading

Suggested reviewers

  • helenKaryamsetty

Poem

In the garden of code, a rabbit hops,
Tidying headers, making manual stops.
With utility magic, requests now flow,
Cookies and agents in neat little rows.
Each hop brings order, each nibble brings cheer,
Refactored and readyβ€”springtime is here! πŸ₯•βœ¨

✨ Finishing Touches
  • πŸ“ Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share
πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (3)
src/main/java/com/iemr/mmu/utils/http/AuthorizationHeaderRequestWrapper.java (2)

11-11: Follow Java naming conventions for instance variables.

The instance variable should use camelCase naming convention rather than PascalCase.

-private final String Authorization;
+private final String authorization;

Remember to update references to this variable in the rest of the class.


18-24: Consider extracting the header name as a constant.

The string "Authorization" is used multiple times in the class. Extracting it as a constant would improve maintainability.

+private static final String AUTHORIZATION_HEADER = "Authorization";

 @Override
 public String getHeader(String name) {
-    if ("Authorization".equalsIgnoreCase(name)) {
-        return Authorization;
+    if (AUTHORIZATION_HEADER.equalsIgnoreCase(name)) {
+        return authorization;
     }
     return super.getHeader(name);
 }
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)

14-40: Add logging to track request entity creation.

Adding logging would help with debugging and monitoring of the request entity creation process.

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;

 public class RestTemplateUtil {
+    private static final Logger logger = LoggerFactory.getLogger(RestTemplateUtil.class);
+
     public static HttpEntity<Object> createRequestEntity(Object body, String authorization) {
+        logger.debug("Creating request entity with authorization: {}", authorization != null);
         
         ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
         if (servletRequestAttributes == null) {
+            logger.debug("No servlet request attributes available, creating basic headers");
             MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
             headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8");
             headers.add(HttpHeaders.AUTHORIZATION, authorization);
             return new HttpEntity<>(body, headers);
         }
+        logger.debug("Servlet request attributes available, creating complete headers");
         HttpServletRequest requestHeader = servletRequestAttributes.getRequest();
         // rest of the method...
     }
 }
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 0b27c16 and 81e0a2a.

πŸ“’ Files selected for processing (15)
  • src/main/java/com/iemr/mmu/service/cancerScreening/CSCarestreamServiceImpl.java (2 hunks)
  • src/main/java/com/iemr/mmu/service/common/master/RegistrarServiceMasterDataImpl.java (2 hunks)
  • src/main/java/com/iemr/mmu/service/common/transaction/CommonDoctorServiceImpl.java (2 hunks)
  • src/main/java/com/iemr/mmu/service/common/transaction/CommonServiceImpl.java (2 hunks)
  • src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerImpl.java (4 hunks)
  • src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerTransactionalImpl.java (3 hunks)
  • src/main/java/com/iemr/mmu/service/dataSyncActivity/UploadDataToServerImpl.java (3 hunks)
  • src/main/java/com/iemr/mmu/service/registrar/RegistrarServiceImpl.java (5 hunks)
  • src/main/java/com/iemr/mmu/service/tele_consultation/TeleConsultationServiceImpl.java (2 hunks)
  • src/main/java/com/iemr/mmu/utils/CookieUtil.java (1 hunks)
  • src/main/java/com/iemr/mmu/utils/JwtUserIdValidationFilter.java (2 hunks)
  • src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1 hunks)
  • src/main/java/com/iemr/mmu/utils/UserAgentContext.java (1 hunks)
  • src/main/java/com/iemr/mmu/utils/http/AuthorizationHeaderRequestWrapper.java (1 hunks)
  • src/main/java/com/iemr/mmu/utils/http/HttpInterceptor.java (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (9)
src/main/java/com/iemr/mmu/service/cancerScreening/CSCarestreamServiceImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
  • RestTemplateUtil (13-42)
src/main/java/com/iemr/mmu/service/dataSyncActivity/UploadDataToServerImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
  • RestTemplateUtil (13-42)
src/main/java/com/iemr/mmu/service/common/transaction/CommonServiceImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
  • RestTemplateUtil (13-42)
src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
  • RestTemplateUtil (13-42)
src/main/java/com/iemr/mmu/service/common/transaction/CommonDoctorServiceImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
  • RestTemplateUtil (13-42)
src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerTransactionalImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
  • RestTemplateUtil (13-42)
src/main/java/com/iemr/mmu/service/common/master/RegistrarServiceMasterDataImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
  • RestTemplateUtil (13-42)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
src/main/java/com/iemr/mmu/utils/UserAgentContext.java (1)
  • UserAgentContext (3-18)
src/main/java/com/iemr/mmu/service/registrar/RegistrarServiceImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
  • RestTemplateUtil (13-42)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (34)
src/main/java/com/iemr/mmu/utils/CookieUtil.java (1)

26-32: Good enhancement to JWT token extraction.

Making getJwtTokenFromCookie static with null-safety checking improves code robustness by preventing NullPointerExceptions when no cookies are present. This change properly supports the centralized JWT token handling across the application.

src/main/java/com/iemr/mmu/utils/http/HttpInterceptor.java (1)

63-66: Good addition of early return for missing Authorization headers.

This early check allows requests without an Authorization header to bypass further validation, which helps optimize request processing. The addition of the log message also aids in debugging and monitoring unauthorized requests.

src/main/java/com/iemr/mmu/service/tele_consultation/TeleConsultationServiceImpl.java (2)

62-62: Good addition of RestTemplateUtil import.

Adding this import supports the refactoring to use the centralized HTTP request entity creation utility.


200-200: Improved HTTP entity creation with centralized utility.

Replacing the manual construction of headers and cookie extraction with the centralized RestTemplateUtil.createRequestEntity method improves code maintainability and consistency. This change aligns with the broader refactoring to standardize HTTP request handling across the application.

src/main/java/com/iemr/mmu/service/common/master/RegistrarServiceMasterDataImpl.java (2)

65-65: Good addition of RestTemplateUtil import.

Adding this import supports the refactoring to use the centralized HTTP request entity creation utility.


228-228: Improved HTTP entity creation with centralized utility.

Replacing the manual construction of headers with the centralized RestTemplateUtil.createRequestEntity method improves code maintainability and consistency. This change aligns with the broader refactoring to standardize HTTP request handling across the application.

src/main/java/com/iemr/mmu/service/cancerScreening/CSCarestreamServiceImpl.java (2)

47-47: Added import for RestTemplateUtil.

The added import supports the refactoring of HTTP entity creation.


67-67: Good refactoring: Centralized HTTP entity creation.

Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method RestTemplateUtil.createRequestEntity. This improves code maintainability and ensures consistent header handling across the application.

src/main/java/com/iemr/mmu/service/dataSyncActivity/UploadDataToServerImpl.java (2)

55-55: Added import for RestTemplateUtil.

The added import supports the refactoring of HTTP entity creation.


376-376: Good refactoring: Centralized HTTP entity creation.

Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method RestTemplateUtil.createRequestEntity. This improves code maintainability and ensures consistent header handling across the application.

src/main/java/com/iemr/mmu/service/common/transaction/CommonServiceImpl.java (3)

82-82: Added import for RestTemplateUtil.

The added import supports the refactoring of HTTP entity creation.


827-827: Good refactoring: Centralized HTTP entity creation in restTemplatePost method.

Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method RestTemplateUtil.createRequestEntity. This improves code maintainability and ensures consistent header handling across the application.


834-834: Good refactoring: Centralized HTTP entity creation in restTemplateGet method.

Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method RestTemplateUtil.createRequestEntity. This ensures consistent header handling for GET requests.

src/main/java/com/iemr/mmu/service/common/transaction/CommonDoctorServiceImpl.java (2)

75-75: Added import for RestTemplateUtil.

The added import supports the refactoring of HTTP entity creation.


910-910: Good refactoring: Centralized HTTP entity creation in callTmForSpecialistSlotBook method.

Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method RestTemplateUtil.createRequestEntity. This ensures consistent header handling for specialist slot booking requests.

src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerImpl.java (4)

56-56: Import added for the new utility class.

The addition of RestTemplateUtil import supports the refactoring of HTTP request entity creation.


189-189: Good refactoring: Centralized HTTP entity creation.

Replacing manual HTTP entity creation with RestTemplateUtil.createRequestEntity improves code maintainability and standardizes header management across the application.


336-336: Consistent usage of the RestTemplateUtil.

The HTTP entity creation is properly refactored to use the central utility method, maintaining consistency with the rest of the codebase.


345-345: Consistent implementation for the second request.

The second HTTP entity creation in the same method is also properly refactored to use RestTemplateUtil, ensuring consistent behavior across all API calls.

src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerTransactionalImpl.java (3)

55-55: Import added for the new utility class.

The addition of RestTemplateUtil import supports the refactoring of HTTP request entity creation in this class.


247-247: Good refactoring: Centralized HTTP entity creation.

Replacing manual HTTP entity creation with RestTemplateUtil.createRequestEntity improves code maintainability and standardizes header management across the application.


271-271: Consistent usage of the RestTemplateUtil for flag updates.

The HTTP entity creation in updateProcessedFlagToCentral method is properly refactored to use the central utility method, maintaining consistency with the rest of the application.

src/main/java/com/iemr/mmu/utils/UserAgentContext.java (1)

1-18: Well-designed ThreadLocal implementation for User-Agent context.

This is a good implementation of a thread-local context for storing User-Agent values, following Java best practices. The ThreadLocal approach ensures thread safety while making the User-Agent available throughout request processing without parameter passing.

The class properly provides methods to set, get, and clear the thread-local storage, which is essential for preventing memory leaks in thread-pooled environments.

src/main/java/com/iemr/mmu/utils/JwtUserIdValidationFilter.java (4)

9-10: Import added for the request wrapper.

The addition of AuthorizationHeaderRequestWrapper import supports the new security enhancement to control Authorization header propagation.


77-80: Security enhancement: Controlled Authorization header propagation.

Wrapping the request with AuthorizationHeaderRequestWrapper and passing an empty authorization header prevents downstream components from accessing the raw Authorization header after JWT validation, which is a good security practice.


82-90: Improved conditional structure for JWT validation.

The restructured conditional logic with improved if-else if-else structure makes the code more readable and maintainable, clearly separating the different authentication scenarios.


91-101: Added support for mobile client authentication.

This new code branch properly handles mobile clients by:

  1. Checking User-Agent header to identify mobile clients
  2. Setting the User-Agent in ThreadLocal context for downstream components
  3. Properly clearing the ThreadLocal in a finally block to prevent memory leaks

The try-finally block ensures proper resource cleanup even if an exception occurs during filter chain processing, which is a best practice.

src/main/java/com/iemr/mmu/service/registrar/RegistrarServiceImpl.java (5)

72-72: Good addition of the required import.

The import of RestTemplateUtil is necessary for the refactoring of HTTP request entity creation in multiple methods.


703-703: Centralizing HTTP request entity creation improves code maintainability.

The refactoring removes duplicate code for manual header construction and standardizes the HTTP request entity creation process.


731-731: Consistent application of the refactoring pattern.

The use of RestTemplateUtil.createRequestEntity here maintains consistency with other REST API calls.


751-751: Streamlined HTTP entity creation.

The standardized approach for creating request entities simplifies the code and reduces potential for errors.


774-774: Consistent implementation of the utility method.

This change completes the refactoring pattern across all REST API calls in the class.

src/main/java/com/iemr/mmu/utils/http/AuthorizationHeaderRequestWrapper.java (1)

1-42: Well-implemented request wrapper for Authorization header handling.

The class follows the standard wrapper pattern for HTTP servlet requests and correctly overrides the necessary methods to handle the Authorization header.

src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)

13-42: Good centralization of HTTP request entity creation logic.

The utility class effectively centralizes the creation of HTTP entities with appropriate headers, improving code maintainability and consistency across the application.

Comment on lines +13 to +16
public AuthorizationHeaderRequestWrapper(HttpServletRequest request, String authHeaderValue) {
super(request);
this.Authorization = authHeaderValue;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Add null check for authorization parameter.

The constructor should validate that the authorization parameter is not null to prevent NullPointerExceptions.

 public AuthorizationHeaderRequestWrapper(HttpServletRequest request, String authHeaderValue) {
     super(request);
+    if (authHeaderValue == null) {
+        throw new IllegalArgumentException("Authorization header value cannot be null");
+    }
     this.Authorization = authHeaderValue;
 }
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/mmu/utils/http/AuthorizationHeaderRequestWrapper.java
around lines 13 to 16, the constructor assigns the authorization parameter
without checking for null, which can cause NullPointerExceptions. Add a null
check for the authHeaderValue parameter at the start of the constructor and
throw an IllegalArgumentException or handle the null case appropriately to
ensure the parameter is not null before assignment.

Comment on lines 36 to 37
headers.add("JwtToken",requestHeader.getHeader("JwtToken"));
headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add null checks for header values.

The code doesn't handle cases where header values might be null, potentially leading to NullPointerException or unexpected behavior.

-headers.add("JwtToken",requestHeader.getHeader("JwtToken"));
-headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
+// Add JwtToken header only if it exists in the request
+String jwtTokenHeader = requestHeader.getHeader("JwtToken");
+if (jwtTokenHeader != null) {
+    headers.add("JwtToken", jwtTokenHeader);
+}
+
+// Add cookie header only if JWT token was successfully extracted
+if (jwtTokenFromCookie != null) {
+    headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
+}
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
headers.add("JwtToken",requestHeader.getHeader("JwtToken"));
headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
// Add JwtToken header only if it exists in the request
String jwtTokenHeader = requestHeader.getHeader("JwtToken");
if (jwtTokenHeader != null) {
headers.add("JwtToken", jwtTokenHeader);
}
// Add cookie header only if JWT token was successfully extracted
if (jwtTokenFromCookie != null) {
headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
}
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java around lines 36 to 37,
add null checks before adding header values to avoid NullPointerException.
Specifically, check if requestHeader.getHeader("JwtToken") and
jwtTokenFromCookie are not null before adding them to headers. If they are null,
either skip adding those headers or handle the null case appropriately to
prevent unexpected behavior.

Comment on lines 25 to 30
try {
jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader);

} catch (Exception e) {
e.printStackTrace();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Improve exception handling for JWT token extraction.

The current implementation catches exceptions but only prints the stack trace without proper logging or fallback mechanism.

try {
    jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader);
} catch (Exception e) {
-   e.printStackTrace();
+   // Use logger instead of printStackTrace
+   logger.error("Error extracting JWT token from cookie", e);
+   // Consider setting a default value or taking appropriate action
}
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader);
} catch (Exception e) {
e.printStackTrace();
}
try {
jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader);
} catch (Exception e) {
// Use logger instead of printStackTrace
logger.error("Error extracting JWT token from cookie", e);
// Consider setting a default value or taking appropriate action
}
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java around lines 25 to 30,
the exception handling for extracting the JWT token from the cookie only prints
the stack trace, which is insufficient. Replace the printStackTrace call with
proper logging of the exception using a logger, and implement a fallback
mechanism such as returning a default value or rethrowing a custom exception to
handle the failure gracefully.

@sonarqubecloud
Copy link

@ravishanigarapu ravishanigarapu merged commit 74d8ebf into PSMRI:develop May 22, 2025
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants